<template>
  <div>
    <div>
      <el-row>
        <el-col :span="22">
          <el-form :inline="true" :model="searchData" class="demo-form-inline">
            <el-form-item label="订单编号">
              <el-input v-model="searchData.orderNumber" placeholder="订单编号"></el-input>
            </el-form-item>
            <el-form-item label="下单时间:">
              <el-date-picker unlink-panels
                              v-model="searchData.createDate"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="orderNumber" label="订单编号" width="200" align="center" sortable>
          <template slot-scope="scope">
            <a href="javascript:void(0)" @click="details(scope.row)">{{scope.row.orderNumber}}</a>
          </template>
        </el-table-column>
        <el-table-column prop="consumer.realName" label="下单用户姓名" width="120" align="center"></el-table-column>
        <el-table-column prop="consumer.phone" label="电话号码" width="120" align="center"></el-table-column>
        <el-table-column prop="createDate" label="下单时间" width="225" align="center" sortable></el-table-column>

        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
<!--            <el-tag v-if="scope.row.payTag === 'K002-3'" type="success">等待取货</el-tag>-->

<!--           查看订单-->
            <el-button @click="viewTheOrder(scope.row)" type="primary" size="small" >查看订单</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <el-dialog title="详情" :visible.sync="dialogFormVisible" width="50%" @close="dialogClose">
        <el-dialog
            width="40%"
            title="退货理由"
            :visible.sync="innerVisible"
            append-to-body>
<!--          显示row中的订单信息-->
          <el-card class="box-card" style="width: 100%;height: 100%">
            <div slot="header">
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-upload
                      class="avatar-uploader"
                      ref="upload"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      @click.native.prevent> <!-- 阻止默认点击行为 -->
                    <div class="grid-content bg-purple">
                      <el-avatar slot="trigger" :size="90" :src="img" @error="errorHandler" @click.native="handleAvatarClick" style="margin: 0 auto">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                      </el-avatar>
                    </div>
                  </el-upload>
                  <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
                </el-col>
              </el-row>
            </div>
            <el-form ref="form" :model="BackForm" :rules="rules" label-width="100px">
              <el-form-item label="理由" prop="backReason">
                <el-input v-model="BackForm.backReason"></el-input>
              </el-form-item>
            </el-form>
          </el-card>

          <div slot="footer" class="dialog-footer">
            <el-button @click="innerVisible = false" >取 消</el-button>
            <el-button type="success" size="small" @click="submitUpload">提交</el-button>
          </div>
        </el-dialog>
        <el-descriptions class="margin-top"  :column="2" size="medium" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              订单编号
            </template>
            {{row.orderNumber}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              下单时间
            </template>
            {{row.createDate}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              收货人姓名
            </template>
            {{row.merchant.name}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              收货人电话
            </template>
            {{row.merchant.phone}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              提货人姓名
            </template>
            {{row.consumer.realName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              提货人电话
            </template>
            {{row.consumer.phone}}
          </el-descriptions-item>
        </el-descriptions>
        <el-table :data="row.orderDetails" border style="width: 100%">
          <el-table-column prop="price" label="商品名称" width="180px" align="center">
            <template slot-scope="scope">
              {{scope.row.product.name}}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="150px" align="center"></el-table-column>
          <el-table-column prop="amount" label="数量" width="150px" align="center"></el-table-column>
          <el-table-column prop="unit" label="单位" width="150px" align="center">
            <template slot-scope="scope">
              {{scope.row.product.unit}}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="总金额" width="150px" align="center"></el-table-column>
        </el-table>
        <el-steps v-if="backTag === 'B001-1'" :active="active" finish-status="success">
          <el-step title="付款"></el-step>
          <el-step title="平台发货"></el-step>
          <el-step title="商户收货"></el-step>
          <el-step title="用户提货"></el-step>
        </el-steps>
        <el-steps v-if="backTag !== 'B001-1'&&active === 4" :active="active2" finish-status="success">
          <el-step title="完成退货理由填写"></el-step>
          <el-step title="商户验收"></el-step>
          <el-step title="平台审核"></el-step>
          <el-step title="退款"></el-step>
        </el-steps>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" >取 消</el-button>
          <el-button v-if="active === 0" @click="pay()" type="success" size="small" >支付</el-button>
          <el-button v-if="active === 0" @click="cancelOrder()" type="danger" size="small" >取消订单</el-button>
          <el-button v-if="active === 4&&backTag === 'B001-1'" @click="returnable" type="success" size="small" >退货</el-button>
          <el-button v-if="active === 4&&backTag === 'B001-2'" @click="reasonForReturn" type="success" size="small" >退货理由</el-button>
          <el-button v-if="active === 4&&backTag === 'B001-2'" @click="NotReturnable()" type="danger" size="small" >取消退货</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserOrder',
  components: {},
  props: {},
  data () {
    return {
      active:1,
      active2:0,
      backTag:'B001-1',
      img: '',
      user:{},
      searchData:{
        orderNumber: '',
        createDate:[]
      },
      tableData: [],
      currentPage : 1,
      total : 0,
      pageSize : 5,
      dialogFormVisible : false,
      innerVisible:false,
      row:{merchant: {name: '', phone: ''}, consumer: {realName: '', phone: ''}, orderDetails: []},
      backProduct:[],
      fileList:[],
      BackForm:{
        backReason:''
      },
      rules: {
        backReason: [
          { required: true, message: '请输入退货理由', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    initUser(){
      this.user = this.$store.state.user;
    },
    handleSizeChange(val) {//页大小改变时
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.InitializeThePage();
    },
    handleCurrentChange(val) {//页码发生改变时
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.InitializeThePage();
    },
    InitializeThePage(){
      Object.assign(this.searchData, {"currentPage": this.currentPage, "pageSize": this.pageSize, "consumerId": this.user.consumerId})
      this.$axios.post('http://localhost:8090/orders/getOrderByMerchantIdOrConsumerId', this.searchData).then(({ data }) => {
        if(data !== null && data !== undefined){
          this.tableData = data.records;
          this.total = data.total;
          console.log(data);
        }else {
          this.$notify({
            title: '警告',
            message: '获取订单失败',
            type: 'warning'
          });
        }
      });
    },
    onSubmit(){
      this.InitializeThePage();
    },
    details(row){
      this.row = row;
      this.dialogFormVisible = true;
      this.detailsOrNot = 'details';
    },
    dialogClose(){
      this.dialogFormVisible = false;
    },
    pay(){
      window.open(`http://localhost:8090/alipay/pay?orderNo=${this.row.orderNumber}`);
    },
    viewTheOrder(row){
      this.row = row;
      this.dialogFormVisible = true;
      if (row.payTag === 'K002-1'||row.payTag === 'K002-2'){
        this.active = 0;
      }else if (row.payTag === 'K002-3'){
        this.active = 1;
      }
      if (row.conveyTag === "P001-2"){
        this.active = 2;
      }else if (row.conveyTag === "P001-3"){
        this.active = 3;
      }else if (row.conveyTag === "P001-4"){
        this.active = 4;
      }
      if(row.backTag === 'B001-1'){
        this.backTag = 'B001-1';
      }else if (row.backTag === 'B001-2'){
        this.backTag = 'B001-2';
      }else if (row.backTag === 'B001-3'){
        this.backTag = 'B001-3';
        this.active2 = 1;
      }else if (row.backTag === 'B001-4'){
        this.backTag = 'B001-4';
        this.active2 = 2;
      }else if (row.backTag === 'B001-5'){
        this.backTag = 'B001-5';
        this.active2 = 3;
      }else if (row.backTag === 'B001-6'){
        this.backTag = 'B001-6';
        this.active2 = 4;
      }
    },
    cancelOrder(){
      this.$axios.get('http://localhost:8090/orders/cancelOrder?orderNumber='+this.row.orderNumber).then(({ data }) => {
        if(data){
          this.$notify({
            title: '成功',
            message: '取消订单成功',
            type: 'success'
          });
          this.InitializeThePage();
        }else {
          this.$notify({
            title: '警告',
            message: '取消订单失败',
            type: 'warning'
          });
        }
      });
    },
    returnable(){
      this.backTag = 'B001-2';
      this.$axios.get('http://localhost:8090/back/updateBackTag?orderNumber='+this.row.orderNumber+'&tag='+this.backTag).then(({ data }) => {
        if(data){
          this.$notify({
            title: '成功',
            message: '退货申请成功',
            type: 'success'
          });
          this.InitializeThePage();
        }else {
          this.$notify({
            title: '警告',
            message: '退货申请失败',
            type: 'warning'
          });
        }
      })
    },
    reasonForReturn(){
      this.innerVisible = true;


    },
    NotReturnable(){
      this.backTag = 'B001-1';
      this.$axios.get('http://localhost:8090/back/updateBackTag?orderNumber='+this.row.orderNumber+'&tag='+this.backTag).then(({ data }) => {
        if(data){
          this.$notify({
            title: '成功',
            message: '取消退货成功',
            type: 'success'
          });
          this.InitializeThePage();
        }else {
          this.$notify({
            title: '警告',
            message: '取消退货失败',
            type: 'warning'
          });
        }
      })
    },
    errorHandler() {
      return true;
    },
    handleAvatarClick() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt500KB = file.size / 1024 < 500;

        if (!isJPGOrPNG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
          return;
        }
        if (!isLt500KB) {
          this.$message.error('上传图片大小不能超过 500KB!');
          return;
        }

        this.img = URL.createObjectURL(file);
        this.fileList = [{ name: file.name, url: this.img, raw: file }];
      }
    },
    submitUpload() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请上传退货商品图片');
            return;
          }

          let formData = new FormData();
          formData.append('consumerId', this.user.consumerId);
          formData.append('orderNumber', this.row.orderNumber);
          formData.append('merchantId', this.row.merchant.merchantId);
          formData.append('totalPrice', this.row.totalPrice);
          formData.append('backReason', this.BackForm.backReason);


          this.fileList.forEach(file => {
            formData.append('files', file.raw);
          });

          this.$axios.post('http://localhost:8090/back/saveBack', formData).then(({ data }) => {
            if(data){
              this.$notify({
                title: '提交成功',
                message: '提交退货理由成功！',
                type: 'success'
              });

              this.innerVisible = false;
              this.dialogFormVisible = false;
              this.backTag = 'B001-3';
              this.$axios.get('http://localhost:8090/back/updateBackTag?orderNumber='+this.row.orderNumber+'&tag='+this.backTag).then(({ data }) => {
                console.log(data);
              })
              this.InitializeThePage();
            }
          }).catch(error => {
            // this.$message.error('注册失败，请稍后重试');
            this.$notify({
              title: '提交失败',
              message: '提交退货理由失败，请稍后重试',
              type: 'warning'
            });
            console.error(error);
          });
        } else {
          // this.$message.error('请检查表单输入是否正确');
          this.$notify({
            title: '提交失败',
            message: '请检查表单输入是否正确',
            type: 'warning'
          });
          return false;
        }
      });
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.initUser();
    this.InitializeThePage();
  },
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>

<style scoped>

</style>
